// pages/guide/main/index.js
const app = getApp()
const utils = require('../../../utils/util.js')
import Toast from '../../../vant-weapp/dist/toast/toast'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    navHeight: app.globalData.navHeight,
    fliterBoxH: 44,
    topTabsList:[],
    topActiveIndex: 0,
    filterShow:false, // 筛选显示 
    filterRows: [], // 组合后的筛选值
    guideList: [],
    fatherCategoryIds:[],
    sonCategoryIds:[],
    hasNoDatas:false,
    isRefresh:false,
    toCrmParams: ''
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     this.setupInit()
    this.getFilterData()
    this.setData({
      toCrmParams: JSON.stringify({ url: '/pages/guide/main/index' })
    })
  },
  async init() {
    const styleList = await  utils.$http(app.globalData.api.GetStyleList, {}, 'GET', true, 'JSON').then(res => {
      return res && res.data
     })
  },

  goBack(){
    wx.navigateBack()
  },
  loadNewData:function(){
    this.data.isRefresh = true;
    this.getGuideData(1)
  },

  // loadMoreData:function(){
  //   this.getGuideData(2)
  // },

  setupInit: function () {
    utils.getFrameById('#navigation', (frame) => {
      // console.log('height:', frame.height)
      if (frame && frame.height) {
        this.setData({
          navHeight: frame.height
        })
      }
    })

    utils.getFrameById('#headerFliters', (frame) => {
      console.log('headerFliters:', frame.height)
      if (frame && frame.height) {
        this.setData({
          fliterBoxH: frame.height
        })
      }
    })
  },

  // 装修攻略列表 1 刷新 ,2,加载更多,
  getGuideData:function(type = 1) {
    const openId = wx.getStorageSync('openId') || ''
    const post = {
      fatherCategoryIds: this.data.fatherCategoryIds,
      sonCategoryIds: this.data.sonCategoryIds
    }
    // utils.json2FormData(post)
    utils.$http(app.globalData.api.GetStrategy, post, 'POST', false, "JSON").then(({success,data,msg}) => {
      if(success === 1){
        if(type === 1){
          this.setData({
            guideList: data,
            isRefresh:false
          })
          // wx.stopPullDownRefresh();
        }  else {
          if(data.length === 0){
              this.setData({
                hasNoDatas:true
              })
          } else {
            const list = this.data.guideList.concat(data)
            this.setData({
              guideList: list,
              hasNoDatas: false
            })
          }
        }
      }
     }).catch(() => {
       this.setData({
         isRefresh: false
       })
     })
  },
    // 筛选接口
    async getFilterData() {
    const res = await utils.$http(app.globalData.api.GetGuideFilter, {}, 'POST', false, "JSON").then(res => {
      return res
    })
     if(res.success === 1) { 
       const {records = []} = res.data
       const ids = records.length > 0 && records[0].childList.map(item => item.id)

        const topTabsList = records.length > 0 && records[0].childList.map(item => {
          return {
            id: item.id,
            name: item.name
          }
        })

        const filterRows =  records.length > 0 && records[0].childList.map(item => {
          const dataList = item.childList.map(list => {
             return {
               id: list.id,
               text: list.name,
               selected: false
             }
           })

           const all = [{
             id: '',
             text: '全部',
             selected: false
           }]
           
           const arr = all.concat(dataList)
           return {
             isSingle : true,
             title: item.name,
             property: item.id,
             dataList : arr
           }
         })

        this.setData({
          fatherCategoryIds: ids,
          filterRows: filterRows,
          topTabsList: topTabsList
        })

        this.getGuideData()
      } else {
        this.setData({
        isRefresh: false
      })
    }
  },
    // 切换tab
    topTabsChange(e) {
      const { id } = e.currentTarget.dataset

      this.data.filterRows.forEach(item =>{
        item.dataList.forEach(v=> {
          v.selected = false
        })
      })

      this.setData({
        topActiveIndex: id,
        fatherCategoryIds: [id],
        sonCategoryIds: []
      })
      this.getGuideData(1)
    },
  // 打开筛选
  openFilter() {
    this.data.filterRows.forEach(item =>{
      if(item.property === this.data.topActiveIndex) {
        const findIdNull = item.dataList.findIndex(v => v.id === '')
        item.dataList[findIdNull].selected = true
      }
    })
    //  console.log(filterRows)
    wx.nextTick((...agrs)=>{
      this.setData({
        filterShow: true,
        filterRows: this.data.filterRows
      })
    })
    // console.log("filterRows:",this.data.filterRows)
  },
  handlerFilterData(filterRows = []) {
    let fatherIds = []
    let sonIds = []

    filterRows.forEach(item =>{
      const sonId =  item.dataList.filter(item => item.selected)
      if(sonId.length) {
        if(sonId[0].id) {
        sonIds.push(sonId[0].id)
        } else {
          fatherIds.push(item.property)
        }
      }
    }) 
    if(fatherIds.length === 0 && sonIds.length === 0) {
      fatherIds = filterRows.map(item => item.property)
    }
    this.setData({
      topActiveIndex: null,
      fatherCategoryIds:fatherIds.filter(item => item),
      sonCategoryIds:sonIds.filter(item => item),
    })

    this.getGuideData(1)
  },
  // 重置
  filterReSet(e) {
    const filterRows = e.detail
    this.setData({
      filterRows: filterRows
    })
    this.handlerFilterData(filterRows)
  },
  
  //确认
  filterConfirm(e){
    const filterRows = e.detail
    this.setData({
      filterRows: filterRows
    })
    this.handlerFilterData(filterRows)
  },
  // 更多
  listItemClick(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/guide/item/index?id=${encodeURIComponent(item.categoryId)}&name=${encodeURIComponent(item.categoryName)}`
    })
  },
  // 详情页
  toDetailPage(e) {
    const item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: `/pages/guide/index/index?id=${encodeURIComponent(item.id)}`
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})